<template>
	<div class="body">
		<div class="title">
			<el-input placeholder="请输入标题" v-model="title" class="input"></el-input>
			<el-button-group class="btn-group">
				<el-button @click="save">存草稿</el-button>
				<el-button v-popover:popover type="primary">发布</el-button>
			</el-button-group>
			<el-popover
					ref="popover"
					placement="right"
					width="400"
					trigger="click">
				<div class="popover-content">
					<div class="title">发布文章</div>
					<div class="latter-title">
						分类
					</div>
					<div class="type-list">
						<div @click="selectType(item.value,index)" v-for="(item,index) in typeList" :key="index" class="type-item" :class="{active:item.active}">{{item.label}}</div>
					</div>
					<div class="latter-title">
						添加标签
					</div>
					<div class="type-list">
						<div v-for="(item,index) in tagList" :key="index" class="type-item">{{item}}</div>
						<div @click="writeTag" class="type-item">
							<span v-show="!isWrite">+添加标签</span>
<!--							<el-input @blur="addTag" v-model="tag" size="mini" v-show="isWrite"></el-input>-->
							<el-select
								size="mini"
								v-show="isWrite"
								v-model="tag"
								filterable
								remote
								reserve-keyword
								placeholder="请输入关键词"
								:remote-method="remoteMethod"
								:loading="loading"
								@change="addTag">
								<el-option
									v-for="item in option"
									:key="item.value"
									:label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</div>
					</div>
					<div class="submit">
						<el-button @click="submit" type="primary">确定并发布</el-button>
					</div>

				</div>
			</el-popover>
		</div>
		<mavon-editor
		:toolbars="markdownOption"
		@save="submit"
		v-model="html"
		class="md-body"
		@imgAdd="$imgAdd"
		@imgDel="$imgDel"
		ref="md"/>
	</div>
</template>
<script>

	import Vue from 'vue'
	import mavonEditor from 'mavon-editor';
	import 'mavon-editor/dist/css/index.css';
	import saveBlog from '@/api/blog/saveBlog.js';
	import uploadBlogImg from '@/api/file/upload.js'
	import {messages} from "../../utils/msg-box";
	import getBlogDetails from '@/api/blog/getBlogDetails.js';
	Vue.use(mavonEditor);
	// 完整版
	// import MarkdownItVue from 'markdown-it-vue'
	// import 'markdown-it-vue/dist/markdown-it-vue.css'
	// 精简版
	// import MarkdownItVueLight from 'markdown-it-vue/dist/markdown-it-vue-light.umd.min.js'
	// import 'markdown-it-vue/dist/markdown-it-vue-light.css'
	export default {
		components: {
			// MarkdownItVue,
			// MarkdownItVueLight
		},
		computed: {
			btn() {
				return this.$store.state.loading;
			}
		},
		created() {
			this.tagListT = this.tagOption.map(item => {
				return { value: item, label: item };
			});
			if(this.blogId) {
				this.getData()
			}
		},
		data() {
			return {
				// html:'# markdown-it-vue ',
				blogId: this.$route.query.id,
				html:'',
				options: {
					markdownIt: {
						linkify: true
					},
					linkAttributes: {
						attrs: {
						target: '_blank',
						rel: 'noopener'
						}
					},
				},
				title:'',
				imgList:[],
				type: '',
				typeList:[
					{
						label: '前端',
						value: 'frontEnd'
					},
					{
						label: 'IOS',
						value: 'ios'
					}
				],
				tagList:[
						// 'vue'
				],
				isWrite:false,
				markdownOption:{
					bold: true, // 粗体
					italic: true, // 斜体
					header: true, // 标题
					underline: true, // 下划线
					strikethrough: true, // 中划线
					mark: true, // 标记
					superscript: true, // 上角标
					subscript: true, // 下角标
					quote: true, // 引用
					ol: true, // 有序列表
					ul: true, // 无序列表
					link: true, // 链接
					imagelink: true, // 图片链接
					code: true, // code
					table: true, // 表格
					fullscreen: true, // 全屏编辑
					readmodel: true, // 沉浸式阅读
					htmlcode: true, // 展示html源码
					help: true, // 帮助
					/* 1.3.5 */
					undo: true, // 上一步
					redo: true, // 下一步
					trash: true, // 清空
					save: true, // 保存（触发events中的save事件）
					/* 1.4.2 */
					navigation: true, // 导航目录
					/* 2.1.8 */
					alignleft: true, // 左对齐
					aligncenter: true, // 居中
					alignright: true, // 右对齐
					/* 2.2.1 */
					subfield: true, // 单双栏模式
					preview: true, // 预览
				},
				btnText:"保存",
				mdContent:'',
				htmlContent:'',
				tag: '',
				option: [],
				tagListT: [],
				loading: false,
				//分类
				tagOption: ["Alabama", "Alaska", "Arizona",
					"Arkansas", "California", "Colorado",
					"Connecticut", "Delaware", "Florida",
					"Georgia", "Hawaii", "Idaho", "Illinois",
					"Indiana", "Iowa", "Kansas", "Kentucky",
					"Louisiana", "Maine", "Maryland",
					"Massachusetts", "Michigan", "Minnesota",
					"Mississippi", "Missouri", "Montana",
					"Nebraska", "Nevada", "New Hampshire",
					"New Jersey", "New Mexico", "New York",
					"North Carolina", "North Dakota", "Ohio",
					"Oklahoma", "Oregon", "Pennsylvania",
					"Rhode Island", "South Carolina",
					"South Dakota", "Tennessee", "Texas",
					"Utah", "Vermont", "Virginia",
					"Washington", "West Virginia", "Wisconsin",
					"Wyoming"]
			};
		},
		methods: {
			// 选择分类
			selectType(id,index) {
				this.typeList.forEach(v => {

					v.active = false
				})
				this.typeList[index].active = true
				this.$forceUpdate()
				this.type = id
			},
			//搜索
			remoteMethod(query) {
				if (query !== '') {
					this.loading = true;

					// 模拟搜索
					setTimeout(() => {
						this.loading = false;
						this.option = this.tagListT.filter(item => {
							return item.label.toLowerCase()
									.indexOf(query.toLowerCase()) > -1;
						});
					}, 200);
				} else {
					this.option = [];
				}
			},
			addTag(val) {
				this.tagList.push(val)
				this.tag = ''
				this.isWrite = false
			},
			writeTag() {
				this.isWrite = true
			},
			async $imgAdd(pos, $file){//将新增图片存入服务器
				let fd = new FormData();
				let _this = this;
				fd.append("file",$file);
				let res = await uploadBlogImg(fd)
				if (res.success){
					_this.$refs.md.$img2Url(pos,res.data.url)
					_this.imgList.push(res.data.url);
				}else {
					messages('error',"图片上传失败，请联系管理员")
				}
			},
			$imgDel(pos){
				let fileUrl = pos[0]
				let index = this.imgList.indexOf(fileUrl);
				this.imgList.splice(index, 1);
			},
			reset() {
				this.html = ''
				messages('success',"清空成功")
			},
			//保存草稿
			async save() {
				let html = this.$refs.md.d_render
				if (!this.checkBlog(html,this.title)){
					return
				}
				let res = await saveBlog({
					title: this.title,
					content: this.html,
					imgList: JSON.stringify(this.imgList),
					html:html,
					type:'2'//保存草稿
				})
				if (res.success){
					messages('success',"保存成功")
				}else {
					messages('error',"保存失败")
				}
			},
			release() {
				messages('success',"发布成功")
			},
			setMakedown() {
                // this.html = converter.makeHtml('# 这是一个标题')
            },
			//提交发布
			async submit(md,html) {
				let _this = this;
				if (html == undefined){
					if (_this.mdContent == ''){
						messages('warning',"请填写内容或保存后发布")
						return
					}
					if (_this.title == ''){
						messages('warning',"请填写标题或保存后发布")
						return
					}
					if (!_this.type){
						messages('warning',"请添加分类")
						return
					}
					if (_this.typeList.length >= 6 || _this.typeList.length < 1){
						messages('warning',"请添加至少1个最多5个标签")
						return
					}
					let res = await saveBlog({
						title: _this.title,
						content: _this.mdContent,
						imgList: JSON.stringify(_this.imgList),
						html:_this.htmlContent,
						type:'1'//发布并保存
					})
					if (res.success){
						messages('success',"发布成功")
					}else {
						messages('error',"发布失败")
					}

				}else {
					if (_this.title == ''){
						messages('warning',"未填写标题")
						return false;
					}
					if (md ==''){
						messages('warning',"未填写内容")
						return false;
					}
					_this.mdContent = md;
					_this.htmlContent = html;
					messages('success',"保存成功")
				}
			},
			async getData() {
				//草稿id
				console.log(this.blogId)
				//获取草稿
				let res = await getBlogDetails({blogId:this.blogId,type:'2'});
				if (res.success){
					this.html = res.data.content
				}else {
					messages("error",res.errMsg)
				}
			},
			checkBlog(content,title) {
				if (title == ''){
					messages('warning',"未填写标题")
					return false;
				}
				if (content == ''){
					messages('warning',"未填写内容")
					return false;
				}
				return true
			}
		}
	}
</script>

<style lang="scss" scoped>

	.body {
		width: 100%;
		min-height: calc(100vh - 100rem);
		flex: 1;
		.title {
			display: flex;
			.btn-group {
				min-width: 124rem;
			}

		}
		.md-body {
			// margin-top: 10rem;
			min-height: calc(100vh - 102rem);
		}

	}
	.popover-content {
		.title {
			font-size: 22rem;
			font-weight: 600;
		}
		.latter-title {
			font-size: 16rem;
			margin-top: 20rem;
			color:#666;
		}
		.type-list {
			display: flex;
			flex-wrap: wrap;
			.type-item {
				font-size: 12rem;
				border: 1px solid #eee;
				padding: 2rem 6rem;
				margin-right: 10rem;
				margin-top: 10rem;
				cursor: pointer;
				transition: all 0.4s;
			}
			.type-item.active {
				border-color: $color;
				color: $color;
			}
		}
		.submit {
			display: flex;
			justify-content: center;
			margin-top: 20rem;
			margin-bottom: 10rem;
		}
	}
</style>
